<style lang="scss" scoped>
* {
  margin: 0;
  padding: 0;
  box-sizing: border-box;
}

body {
  width: 100%;
  height: 100%;
}

.waike {
  position: absolute;
  left: 0;
  // padding: 8% 0;
  width: 75%;
  height: 100%;
  background-color: #333;
  display: flex;
  justify-content: center;
  /* 水平居中 */
  align-items: center;

  video-player {
    max-width: 100%;
    /* 防止视频宽度超出容器 */
    height: auto;
    /* 保持视频的原始宽高比 */
    border: 0;
  }
}

.NavBar {
  width: 25%;
  height: 100%;
  position: absolute;
  right: 0;
  color: #fff;
}

.NavBar-title {
  width: 100%;
  height: 8%;
  background-color: #333;
  display: flex;
  align-items: center;
  /* 垂直居中 */
  text-indent: 20px;
  padding-right: 20px;

  img {
    width: 20px;
    margin-left: auto;
  }

  span {
    margin-left: 60px;
    font-size: 16px;
    color: rgb(214, 90, 100);
    cursor: pointer;
  }
}

.NavBar-content {
  overflow-y: auto;
  width: 100%;
  height: 92%;
  background-color: rgba(0, 0, 0, 0.7);
}

.videobfb {
  background-image: url("@/assets/img/wancheng.svg");
  background-position: 36px center;
  background-repeat: no-repeat;
}

.active {
  background-image: url("@/assets/img/living.png");
  background-repeat: no-repeat;
  background-position: 40px center;
  background-size: 16px;
}

// //禁用视频进度条
// :deep(.vjs-progress-control) {
//   pointer-events: none !important;
// }

.chapter {
  color: #fff;

  .chapter-title {
    display: flex;
    align-items: center;
    /* 垂直居中 */
  }

  span {
    width: 96%;
    height: 40px;
    line-height: 40px;
    white-space: nowrap;
    overflow: hidden;
    text-overflow: ellipsis;
    font-size: 18px;
    // display: block;
  }

  img {
    width: 16px;
    line-height: 30px;
    float: left;
    margin: 0 10px;
  }

  ul {
    list-style: none;

    img {
      width: 16px;
      line-height: 40px;
    }

    li {
      display: flex;
      align-items: center;
      width: 100%;
      overflow: hidden;
      line-height: 40px;
      padding-left: 30px;
      font-size: 16px;
      cursor: pointer;
      // background-image: url("@/assets/img/wancheng.svg");
      // background-position: 36px center;
      // background-repeat: no-repeat;
      text-indent: 30px;
    }

    li:hover {
      //文字放大0.1
      font-size: 18px;
      background-color: #333;
    }
  }
}

.NavBar-hide {
  width: 4%;
  height: 100%;
  /* 垂直居中 */
  position: absolute;
  right: 0;
  display: none;
  background-color: #000;

  img {
    position: absolute;
    top: 50%;
    left: 50%;
    /* 如果也需要水平居中 */
    transform: translate(-50%, -50%);
    /* 偏移自身的50%来实现居中 */
    max-width: 100%;
    /* 防止图片超出容器宽度 */
    height: auto;
    /* 保持图片宽高比 */
  }
}

//videojs大播放按钮的位置
:deep(.video-js .vjs-big-play-button) {
  // background-image: url("@/assets/img/play.png");
  background-color: transparent;
  background-position: center;
  background-repeat: no-repeat;

  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
}
</style>
<template>
  <main class="waike">
    <!-- 监听播放结束：@ended 
    监听视频播放进度：@timeupdate
    监听视频暂停：@pause -->
    <video-player :src="videoSrc" :options="playerOptions" :volume="1" class="playInfo" @play="playVideo"
      @ended="onVideoEnded" @timeupdate="onCurrentTime" @pause="onVideoPause" />
  </main>
  <!-- 导航栏 -->
  <div class="NavBar">
    <div class="NavBar-title">
      <h2>视频课程</h2>
      <span @click="backToCourseDetail">返回课程列表</span>
      <img src="@/assets/img/close.png" @click="closeNavBar()" />
    </div>
    <div class="NavBar-content">
      <div class="chapter" v-for="(chapter, index) in chapters" :key="index">
        <div class="chapter-title" @click="toggleChapter(index)">
          <img :src="chapter.imagePath" alt="Toggle" />
          <span>{{ chapter.title }}</span>
        </div>
        <ul v-if="chapter.isVisible">
          <li v-for="item in chapter.items" :key="item" class="videoList" :class="{
            videobfb: item.videobfb,
            active: activeIndex === item.videoId,
          }" @click="toggleActive(item)">
            {{ item.videoName }}
          </li>
        </ul>
      </div>
    </div>
  </div>
  <!-- 隐藏的导航栏 -->
  <div class="NavBar-hide" @click="openNavBar()">
    <img src="@/assets/img/left.png" />
  </div>
</template>

<script setup>
// document.addEventListener('keydown', function (e) {
//   if (e.key === "F12") {
//     e.preventDefault();
//     return false;
//   }
//   // 也可以添加对 Ctrl+Shift+I, Ctrl+Shift+J 等快捷键的监听  
//   if (e.ctrlKey && e.shiftKey && (e.key === "I" || e.key === "J")) {
//     e.preventDefault();
//     return false;
//   }
// }, true);

// document.addEventListener('contextmenu', event => event.preventDefault());
// 获取小节列表
import { selectChapterList } from "@/api/chapter";
import { selectSectionList } from "@/api/section";
// 获取小节视频列表
import {
  getVideoListService,
  getVideoJdList,
  addVideoJd,
  insertVideoJd,
  selectVideoPath
} from "@/api/video";
import { ref, reactive, onMounted } from "vue";

import { useRoute } from "vue-router";
import router from "@/router";
const route = useRoute();
const courseId = route.query.courseId;
const videoId = route.query.videoId;

// 视频链接地址
const videoSrc = ref()

//获取视频链接地址
const getVideoPath = async () => {
  // console.log(videoId);
  const res = await selectVideoPath(videoId);
  // console.log(res.data);
  videoSrc.value = res.data;
}
getVideoPath();
// 视频播放器配置
let playerOptions = ref({
  playbackRates: [0.5, 1.0, 1.5, 1.75, 2], // 播放速度
  autoplay: true, // 如果true,浏览器准备好时开始回放。
  poster: "../src/assets/img/poster.png", //大播放按钮背景
  muted: false, // 默认情况下将会消除任何音频。
  loop: false, // 导致视频一结束就重新开始。
  preload: "auto", // 建议浏览器在<video>加载元素后是否应该开始下载视频数据。auto浏览器选择最佳行为,立即开始加载视频（如果浏览器支持）
  language: "zh-CN",
  aspectRatio: "16:9", // 将播放器置于流畅模式，并在计算播放器的动态大小时使用该值。值应该代表一个比例 - 用冒号分隔的两个数字（例如"16:9"或"4:3"）
  fluid: true, // 当true时，Video.js player将拥有流体大小。换句话说，它将按比例缩放以适应其容器。
  notSupportedMessage: "此视频暂无法播放，请稍后再试", // 允许覆盖Video.js无法播放媒体源时显示的默认信息。
  controls: true, //控制栏
  controlBar: {
    timeDivider: true, //时间显示
    durationDisplay: true, //显示时间
    remainingTimeDisplay: false, //剩余时间
    fullscreenToggle: true, // 全屏按钮
  },
});

const closeNavBar = () => {
  document.querySelector(".NavBar").style.display = "none";
  document.querySelector(".NavBar-hide").style.display = "block";
  document.querySelector(".waike").style.height = "100%";
  document.querySelector(".waike").style.width = "96%";
  document.querySelector(".waike").style.padding = "8%";
};
const openNavBar = () => {
  document.querySelector(".NavBar").style.display = "block";
  document.querySelector(".NavBar-hide").style.display = "none";
  document.querySelector(".waike").style.width = "75%";
  document.querySelector(".waike").style.padding = "0";
};

const chapters = reactive([]);

function toggleChapter(index) {
  chapters[index].isVisible = !chapters[index].isVisible;
  //更换图片path
  if (chapters[index].isVisible) {
    chapters[index].imagePath = "./assets/img/down.png";
  } else {
    chapters[index].imagePath = "./assets/img/right.png";
  }
}
onMounted(async () => {
  //获取视频链接地址
  //根据课程编号获取章节列表
  const res = await selectChapterList(route.query.courseId);
  // console.log(res.data);
  //res：章节列表   1:课程id
  //循环遍历所有章节
  if (res.data.length >= 1) {
    for (let i = 0; i < res.data.length; i++) {
      // console.log(res.data[i].chapterId + "-=====");
      // console.log(res.data[i])
      if (res.data[i].chapterId) {
        const sectionRes = await selectSectionList(res.data[i].chapterId);
        // console.log(sectionRes.data)
        //循环遍历所有小节
        if (sectionRes.data.length >= 1) {
          for (let j = 0; j < sectionRes.data.length; j++) {
            //添加小节列表
            chapters.push({
              title: sectionRes.data[j].sectionName,
              items: [],
              imagePath: "./assets/img/right.png",
            });
            //根据小节id获取小节视频列表
            const videoRes = await getVideoListService(
              sectionRes.data[j].sectionId
            );
            //循环遍历所有小节视频
            for (let k = 0; k < videoRes.data.length; k++) {
              //添加每个小节下的视频
              chapters[chapters.length - 1].items.push(videoRes.data[k]);
              //判断小节视频是否已经观看
              if (chapters[chapters.length - 1].items[k].videoId != null) {
                const resVideoJd = await getVideoJdList(
                  chapters[chapters.length - 1].items[k].videoId
                );
                if (resVideoJd.data == 100) {
                  // console.log("进度为100的:",videobfbIndex.value)
                  chapters[chapters.length - 1].items[k].videobfb = true;
                }
              }
            }
          }
        }
      }
    }
  }
});

const loadVideoList = async () => {
  for (let i = 0; i < chapters.length; i++) {
    for (let k = 0; k < chapters[i].items.length; k++) {
      const resVideoJd = await getVideoJdList(chapters[i].items[k].videoId);
      if (resVideoJd.data == 100) {
        // console.log("进度为100的:",videobfbIndex.value)
        chapters[i].items[k].videobfb = true;
      }
    }
  }
};

//返回上级目录
const backToCourseDetail = () => {
  history.go(-1);
};

//视频播放结束
const onVideoEnded = async () => {
  //console.log("视频播放结束",event.target.currentTime);
  addVideoJd(videoId);
  loadVideoList();
};
// 获取当前播放时间
const onCurrentTime = () => {
  // console.log(
  //   "当前播放时间：",  event.target.currentTime,
  //   "视频总时长",   event.target.duration,
  //   "当前播放进度",  Math.round((event.target.currentTime / event.target.duration) * 100)
  // );
  if(event.target.currentTime!=undefined && event.target.duration!=undefined){
    insertVideoJd(
    videoId,
    Math.round((event.target.currentTime / event.target.duration) * 100)
  );
  }
  
};

const activeIndex = ref(null); // 使用 ref 创建一个响应式引用，初始值为 null

// 方法：切换活动视频
function toggleActive(item) {
  activeIndex.value = activeIndex.value === item.videoId ? null : item.videoId;
  videoSrc.value = item.videoPath;
  videoId = item.videoId;
}
// 视频暂停
const onVideoPause = () => {
  // console.log("视频暂停",event.target.currentTime);
  // console.log("视频编号",videoId.value)
  insertVideoJd(
    videoId,
    ((event.target.currentTime / event.target.duration) * 100) | 0
  );
};
</script>
